package com.metronoteapp.dialog;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.metronoteapp.MainActivity;
import com.metronoteapp.R;
import com.metronoteapp.database.GroupNoteDao;
import com.metronoteapp.database.NoteDao;
import com.metronoteapp.model.GroupModel;
import com.metronoteapp.model.NoteModel;
import com.metronoteapp.until.AudioRecorderUntil;
import com.metronoteapp.until.Constants;

public class RecordingAudioDialog extends Dialog implements
		android.view.View.OnClickListener {
	private String TAG = RecordingAudioDialog.class.getSimpleName();
	private Context mContext;
	private TextView txtTitle;
	private Button btnStart;
	private Button btnStop;
	private Button btnSave;
	private Dialog dialog;
	private Button btnExit;
	private String txtGroup;
	private ImageView imgRecord;
	private GroupNoteDao mObjGroupDao;
	private GroupModel mObjGroupModel;
	private List<String> choices;
	private Spinner spnGroupNote;
	private AudioRecorderUntil mObjRecord;
	private NoteModel mObjNoteModel;
	private NoteDao mObjNoteDao;
	private Boolean mBlnRecording;
	private Boolean mBlnSave;

	public RecordingAudioDialog(Context context) {
		super(context);
		mContext = context;
	}

	public void displaydialog() {
		mBlnRecording = false;
		mBlnSave = false;
		dialog = new Dialog(mContext);
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		WindowManager.LayoutParams lp = this.getWindow().getAttributes();
		lp.dimAmount = 0;
		dialog.setContentView(R.layout.layout_add_new_note_audio);
		dialog.getWindow().getAttributes().windowAnimations = R.style.DialogAnimation;

		txtTitle = (TextView) dialog.findViewById(R.id.txtTitleAudioNote);
		btnSave = (Button) dialog.findViewById(R.id.btnSaveAudio);
		btnStop = (Button) dialog.findViewById(R.id.btnStopRecording);
		btnStart = (Button) dialog.findViewById(R.id.btnStartRecording);
		imgRecord = (ImageView) dialog.findViewById(R.id.imgRecording);
		btnExit = (Button) dialog.findViewById(R.id.btnExitRecording);
		mObjRecord = new AudioRecorderUntil();

		btnStop.setOnClickListener(this);
		btnSave.setOnClickListener(this);
		btnStart.setOnClickListener(this);
		btnExit.setOnClickListener(this);
		btnStop.setEnabled(false);
		btnStart.setEnabled(true);
		btnStart.setText("Start");
		btnStart.setBackgroundResource(R.color.BackGroundAddGroupButton);

		// Setting spinner
		setGroupDataForSpinner();
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(mContext,
				android.R.layout.simple_dropdown_item_1line, choices);
		spnGroupNote = (Spinner) dialog.findViewById(R.id.spinner1);
		spnGroupNote.setAdapter(adapter);

		dialog.setOnKeyListener(new Dialog.OnKeyListener() {

			@Override
			public boolean onKey(DialogInterface arg0, int arg1, KeyEvent arg2) {
				// TODO Auto-generated method stub

				if (arg1 == KeyEvent.KEYCODE_BACK) {
					if (mBlnRecording == true || mBlnSave == false) {
						File myFile = new File(Constants.PATH_AUDIO + "/"
								+ txtTitle.getText().toString().trim() + ".wav");
						if (myFile.exists()) {
							myFile.delete();
							dialog.dismiss();
						}
					}
					if (mBlnSave == true) {
						dialog.dismiss();
						Intent callMainNote = new Intent(mContext,
								MainActivity.class);
						mContext.startActivity(callMainNote);
					}
				}
				return false;
			}
		});

		dialog.show();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btnSaveAudio:
			saveRecording();
			break;
		case R.id.btnStopRecording:
			stopRecording();
			break;
		case R.id.btnStartRecording:
			startRecording();
			break;
		case R.id.btnExitRecording:
			if (mBlnRecording == true || mBlnSave == false) {
				File myFile = new File(Constants.PATH_AUDIO + "/"
						+ txtTitle.getText().toString().trim() + ".wav");
				if (myFile.exists()) {
					myFile.delete();
					dialog.dismiss();
				}
			}
			if (mBlnRecording == false || mBlnSave == true) {
				dialog.dismiss();
				Intent callMainNote = new Intent(mContext, MainActivity.class);
				mContext.startActivity(callMainNote);
			}
			break;
		default:
			break;
		}
	}

	/*
	 * Function save record after recording
	 */
	public void startRecording() {

		String strTitle = txtTitle.getText().toString().trim();
		Boolean isSDPresent = android.os.Environment.getExternalStorageState()
				.equals(android.os.Environment.MEDIA_MOUNTED);

		if (isSDPresent) {
			if (strTitle.equalsIgnoreCase("")) {
				Toast.makeText(mContext,
						"Please input title before start recording!.",
						Toast.LENGTH_SHORT).show();
			} else {
				imgRecord.setBackgroundResource(R.drawable.recording_act);
				btnStart.setEnabled(false);
				txtTitle.setEnabled(false);
				btnStart.setText("Recording...");
				btnStart.setBackgroundResource(R.drawable.all_note_select);

				// Start record
				mObjRecord.startRecording(strTitle);
				btnStop.setEnabled(true);
				mBlnRecording = true;
				mBlnSave = false;
			}
		} else {
			Toast.makeText(mContext, "SD Card Not found!.", Toast.LENGTH_SHORT)
					.show();
		}

	}

	/*
	 * Function stop recording
	 */
	public void stopRecording() {
		String strTitle = txtTitle.getText().toString().trim();
		imgRecord.setBackgroundResource(R.drawable.recording);
		btnStop.setEnabled(false);
		btnStart.setEnabled(true);
		txtTitle.setEnabled(false);
		btnStart.setText("Start");
		btnStart.setBackgroundResource(R.color.BackGroundAddGroupButton);

		// Stop record
		mObjRecord.stopRecording();
		mBlnRecording = false;
		mBlnSave = false;
	}

	/*
	 * Function start recording
	 */
	public void saveRecording() {
		int intGroupId;
		txtGroup = (String) spnGroupNote.getItemAtPosition(spnGroupNote
				.getSelectedItemPosition());
		if (txtTitle.getText().toString().trim().equalsIgnoreCase("")) {
			Toast.makeText(mContext, "Error: Title is null.",
					Toast.LENGTH_SHORT).show();
		} else {
			mObjGroupDao = new GroupNoteDao(mContext);
			mObjGroupDao.openDB();
			mObjGroupModel = new GroupModel();
			mObjGroupModel.setGroupName(txtGroup);
			Cursor mCursor = mObjGroupDao.getGroupByName(mObjGroupModel);
			if (mCursor.moveToFirst()) {
				do {
					intGroupId = Integer
							.parseInt(getColumnAsString(mCursor, 0));
				} while (mCursor.moveToNext());
			} else {
				intGroupId = 0;
			}
			Log.v(TAG, "saveNewNote() | GroupID add : " + intGroupId);
			mObjGroupDao.closeDB();

			// Update or insert note
			Date cDate = new Date();
			String fDate = new SimpleDateFormat("yyyy-MM-dd").format(cDate);
			mObjNoteDao = new NoteDao(mContext);
			mObjNoteDao.openDB();
			mObjNoteModel = new NoteModel();
			mObjNoteModel.setTitle(txtTitle.getText().toString().trim());
			mObjNoteModel.setContent(Constants.PATH_AUDIO + "/"
					+ txtTitle.getText().toString().trim() + ".wav");
			mObjNoteModel.setGroupId(intGroupId);
			mObjNoteModel.setFlgFav(0);
			mObjNoteModel.setNoteType(Constants.TYPE_AUDIO);
			mObjNoteModel.setDateTime(fDate);
			mObjNoteDao.insertNote(mObjNoteModel);
			mObjNoteDao.closeDB();
			mBlnSave = true;
			mBlnRecording = false;
			txtTitle.setText("");
			Toast.makeText(mContext, "Saved.", Toast.LENGTH_SHORT).show();
		}
	}

	/*
	 * This function parse cursor
	 */
	private static String getColumnAsString(Cursor cursor, int index) {
		return cursor.getString(index).trim();
	}

	public void setGroupDataForSpinner() {
		mObjGroupDao = new GroupNoteDao(mContext);
		choices = new ArrayList<String>();
		mObjGroupDao.openDB();
		Cursor mCursor = mObjGroupDao.getAllRecord();
		Log.v(TAG, "setGroupDataForSpinner() | " + mCursor.getCount());
		if (mCursor.moveToFirst()) {
			do {
				Log.v(TAG, "setGroupDataForSpinner() | Valued: "
						+ getColumnAsString(mCursor, 1));
				choices.add(getColumnAsString(mCursor, 1));
			} while (mCursor.moveToNext());
		}
		mObjGroupDao.closeDB();
	}
}
